package com.skyline.energy.provider.spring;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.SqlTypeValue;
import org.springframework.jdbc.core.StatementCreatorUtils;

public final class PreparedStatementCreatorFactory {
	private PreparedStatementCreatorFactory() {
		
	}
	
	public static PreparedStatementCreator createPreparedStatementCreator(final String sql, final boolean returnKeys) {
		PreparedStatementCreator creator = new PreparedStatementCreator() {

			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql);
				if (returnKeys) {
					ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
				} else {
					ps = con.prepareStatement(sql);
				}

				return ps;
			}

		};
		return creator;
	}

	public static PreparedStatementCreator createPreparedStatementCreator(final String sql, final Object[] args,
			final boolean returnKeys) {
		PreparedStatementCreator creator = new PreparedStatementCreator() {

			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql);
				if (returnKeys) {
					ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
				} else {
					ps = con.prepareStatement(sql);
				}

				if (args != null) {
					for (int i = 0; i < args.length; i++) {
						Object arg = args[i];
						if (arg instanceof SqlParameterValue) {
							SqlParameterValue paramValue = (SqlParameterValue) arg;
							StatementCreatorUtils.setParameterValue(ps, i + 1, paramValue, paramValue.getValue());
						} else {
							StatementCreatorUtils.setParameterValue(ps, i + 1, SqlTypeValue.TYPE_UNKNOWN, arg);
						}
					}
				}
				return ps;
			}
		};
		return creator;
	}
}
